<template>
  <div>
    <Spin :spinning="state.isSpinning">
      <Card title="模块信息" :bordered="false" style="margin-bottom: 10px" :headStyle="headStyle">
        <template #extra>
          <Space>
            <a-button type="primary" @click="handleOk" :loading="state.loading">确定 </a-button>
            <a-button type="default" @click="handleOpen">打开 </a-button>
            <a-button type="default" @click="handleAllModule">全部模块 </a-button>
          </Space>
        </template>
        <BasicForm @register="registerForm">
          <template #msgProp="{ model, field }">
            <a-button
              :type="model[field] && model[field].length ? 'primary' : 'default'"
              @click="handleReminderPersonnelModal(model[field])"
            >
              <SettingOutlined title="配置" />
            </a-button>
          </template>

          <template #fieldTreeShow="{ model, field }">
            <TreeSelect
              class="w-full"
              :tree-data="fieldsByBasicTreeData"
              :field-names="{ label: 'title', value: 'name' }"
              :show-search="true"
              treeNodeFilterProp="title"
              v-model:value="model[field]"
            />
          </template>
          <template #fieldTreeList="{ model, field }">
            <TreeSelect
              class="w-full"
              :tree-data="fieldsByBasicTreeData"
              :field-names="{ label: 'title', value: 'name' }"
              :show-search="true"
              treeNodeFilterProp="title"
              v-model:value="model[field]"
            />
          </template>
          <template #dateField>
            <FormItemRest>
              <div class="flex gap-2 items-center">
                开始日期：
                <TreeSelect
                  :tree-data="fieldsByDates"
                  :field-names="{ label: 'title', value: 'name' }"
                  :show-search="true"
                  treeNodeFilterProp="title"
                  v-model:value="dataRef['fieldBeginDate']"
                  style="flex: 1"
                />
                结束日期：
                <TreeSelect
                  :tree-data="fieldsByDates"
                  :field-names="{ label: 'title', value: 'name' }"
                  :show-search="true"
                  treeNodeFilterProp="title"
                  v-model:value="dataRef['fieldEndDate']"
                  style="flex: 1"
                />
              </div>
            </FormItemRest>
          </template>
          <template #gridShowFieldSelect>
            <FormItemRest>
              <TreeSelect
                :tree-data="formGetFieldsData"
                :field-names="{ label: 'title', value: 'name' }"
                :show-search="true"
                treeNodeFilterProp="title"
                v-model:value="dataRef['gridShowField']"
                style="flex: 1"
                multiple
              />
            </FormItemRest>
          </template>
          <template #showField>
            <FormItemRest>
              <div class="flex gap-2 items-center">
                名称：
                <TreeSelect
                  :tree-data="formGetFieldsData"
                  :field-names="{ label: 'title', value: 'name' }"
                  :show-search="true"
                  treeNodeFilterProp="title"
                  v-model:value="dataRef['fieldName']"
                  style="flex: 1"
                />
                描述：
                <TreeSelect
                  :tree-data="formGetFieldsData"
                  :field-names="{ label: 'title', value: 'name' }"
                  :show-search="true"
                  treeNodeFilterProp="title"
                  v-model:value="dataRef['fieldDesc']"
                  style="flex: 1"
                />
                标签：
                <TreeSelect
                  :tree-data="formGetFieldsData"
                  :field-names="{ label: 'title', value: 'name' }"
                  :show-search="true"
                  treeNodeFilterProp="title"
                  v-model:value="dataRef['fieldLabel']"
                  style="flex: 1"
                />
              </div>
            </FormItemRest>
          </template>

          <template #btnDisplayShow="{ model, field }">
            <FormItemRest>
              <div class="flex_gap">
                <Select
                  :options="showHideOptions"
                  v-model:value="model[field]"
                  placeholder="请选择"
                  style="width: 70px"
                />
                <Input
                  v-model:value="dataRef.btnDisplayName"
                  placeholder="请输入"
                  class="flex_gap_flex_1"
                />

                <a-button
                  :type="
                    dataRef.btnDisplayCond && dataRef.btnDisplayCond.length ? 'primary' : 'default'
                  "
                  @click="handleConfiguration('btnDisplayCond')"
                >
                  <SettingOutlined title="配置" />
                </a-button>
              </div>
            </FormItemRest>
          </template>

          <template #btnAddShow="{ model, field }">
            <FormItemRest>
              <div class="flex_gap">
                <Select
                  :options="showHideOptions"
                  v-model:value="model[field]"
                  placeholder="请选择"
                  style="width: 70px"
                />
                <Input
                  v-model:value="dataRef.btnAddName"
                  placeholder="请输入"
                  class="flex_gap_flex_1"
                />
              </div>
            </FormItemRest>
          </template>
          <template #btnEditShow="{ model, field }">
            <FormItemRest>
              <div class="flex_gap">
                <Select
                  :options="showHideOptions"
                  v-model:value="model[field]"
                  placeholder="请选择"
                  style="width: 70px"
                />
                <Input
                  v-model:value="dataRef.btnEditName"
                  placeholder="请输入"
                  class="flex_gap_flex_1"
                />

                <a-button
                  :type="dataRef.btnEditCond && dataRef.btnEditCond.length ? 'primary' : 'default'"
                  @click="handleConfiguration('btnEditCond')"
                >
                  <SettingOutlined title="配置" />
                </a-button>
              </div>
            </FormItemRest>
          </template>
          <template #btnFlowShow="{ model, field }">
            <FormItemRest>
              <div class="flex_gap">
                <Select
                  :options="showHideOptions"
                  v-model:value="model[field]"
                  placeholder="请选择"
                  style="width: 70px"
                />
                <Input
                  v-model:value="dataRef.btnFlowName"
                  placeholder="请输入"
                  class="flex_gap_flex_1"
                />

                <a-button
                  :type="dataRef.btnFlowCond && dataRef.btnFlowCond.length ? 'primary' : 'default'"
                  @click="handleConfiguration('btnFlowCond')"
                >
                  <SettingOutlined title="配置" />
                </a-button>
              </div>
            </FormItemRest>
          </template>
          <template #btnDelShow="{ model, field }">
            <FormItemRest>
              <div class="flex_gap">
                <Select
                  :options="showHideOptions"
                  v-model:value="model[field]"
                  placeholder="请选择"
                  style="width: 70px"
                />
                <Input
                  v-model:value="dataRef.btnDelName"
                  placeholder="请输入"
                  class="flex_gap_flex_1"
                />

                <a-button
                  :type="dataRef.btnDelCond && dataRef.btnDelCond.length ? 'primary' : 'default'"
                  @click="handleConfiguration('btnDelCond')"
                >
                  <SettingOutlined title="配置" />
                </a-button>
              </div>
            </FormItemRest>
          </template>
          <template #exportColSize="{ model, field }">
            <FormItemRest>
              <Space>
                <span> {{ model[field] || 0 }}个 </span>
                <Popconfirm
                  placement="bottom"
                  :title="'确定要清空吗？'"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handlecCearExportColProps(field)"
                >
                  <a-button type="primary" title="清空上次选择列导出时记录的字段"
                    >清空字段
                  </a-button>
                </Popconfirm>
              </Space>
            </FormItemRest>
          </template>

          <template #isColCheckboxShow="{ model, field }">
            <FormItemRest>
              <div class="flex_gap">
                <Select
                  :options="isColCheckboxShowOptions"
                  v-model:value="model[field]"
                  placeholder="请选择"
                  style="flex: 1"
                />

                <a-button
                  :type="
                    dataRef.checkboxCond && dataRef.checkboxCond.length ? 'primary' : 'default'
                  "
                  title="不满足条件则灰化显示"
                  @click="handleConfiguration('checkboxCond')"
                  v-if="model[field]"
                >
                  <SettingOutlined title="不满足条件则灰化显示" />
                </a-button>
              </div>
            </FormItemRest>
          </template>
        </BasicForm>
      </Card>
      <ViewList
        :formCode="formCode"
        :moduleCode="moduleCode"
        :headStyle="headStyle"
        style="margin-bottom: 10px"
      />
      <TotalField
        :formCode="formCode"
        :moduleCode="moduleCode"
        :headStyle="headStyle"
        style="margin-bottom: 10px"
      />
      <FilterConditions
        :moduleCode="moduleCode"
        :formCode="formCode"
        :headStyle="headStyle"
        :formGetFieldsData="formGetFieldsData"
        style="margin-bottom: 10px"
      />
      <!-- <IconLine
        :moduleCode="moduleCode"
        :formCode="formCode"
        :headStyle="headStyle"
        :formGetFieldsData="formGetFieldsData"
        style="margin-bottom: 10px"
      /> -->
      <RowStyle
        :moduleCode="moduleCode"
        :headStyle="headStyle"
        :formGetFieldsData="formGetFieldsData"
        style="margin-bottom: 10px"
      />
      <FieldTagConfig
        :moduleCode="moduleCode"
        :headStyle="headStyle"
        :formGetFieldsData="formGetFieldsData"
        style="margin-bottom: 10px"
      />

      <NavigationTab
        :headStyle="headStyle"
        :moduleCode="moduleCode"
        :formCode="formCode"
        style="margin-bottom: 10px"
      />
      <OperationColumnLink
        :headStyle="headStyle"
        :moduleCode="moduleCode"
        :formCode="formCode"
        style="margin-bottom: 10px"
        :formGetFieldsData="formGetFieldsData"
      />
      <ButtonList
        :headStyle="headStyle"
        :moduleCode="moduleCode"
        :formCode="formCode"
        style="margin-bottom: 10px"
        :formGetFieldsData="formGetFieldsData"
      />
    </Spin>
    <ConfigurationModal
      @register="registerModalConfiguration"
      @success="handleSuccessConfiguration"
    />
    <ReminderPersonnelModal
      @register="registerModalReminderPersonnelModal"
      @success="handleSuccessReminderPersonnelModal"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick, watch } from 'vue';
  import { Spin, Space, Popconfirm, Form, Select, Input, Card, TreeSelect } from 'ant-design-vue';
  import { SettingOutlined } from '@ant-design/icons-vue';
  import {
    formSchema,
    State,
    showHideOptions,
    setFormData,
    isColCheckboxShowOptions,
  } from './setupComponent.data';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useModal } from '/@/components/Modal';
  import ConfigurationModal from '../configuration/index';
  import ReminderPersonnelModal from './reminderPersonnelModal/index.vue';
  import { headStyle } from '/@/views/pages/managerPage/managerPage.data';
  import {
    getVisualGetModuleProps,
    getVisualSetModuleProps,
    getVisualClearExportColProps,
    getVisualSetMsgProp,
  } from '/@/api/module/module';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ViewList from './viewList/index.vue';
  import TotalField from './totalField/index.vue';
  import FilterConditions from './filterConditions/index.vue';
  import IconLine from './iconLine/index.vue';
  import NavigationTab from './navigationTab/index.vue';
  import OperationColumnLink from './operationColumnLink/index.vue';
  import ButtonList from './buttonList/index.vue';
  import RowStyle from './rowStyle/index.vue';
  import FieldTagConfig from './fieldTagConfig/index.vue';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import {
    getFormGetFieldsByBasicTree,
    getFormGetFieldsByDate,
  } from '/@/api/formDesign/formDesign';
  import { useGo } from '/@/hooks/web/usePage';
  import { getFormViewList } from '/@/api/formDesign/formDesign';
  import { useRouter } from 'vue-router';

  const { currentRoute } = useRouter();
  const FormItemRest = Form.ItemRest;
  const props = defineProps({
    formCode: {
      type: String,
      default: '',
    },
    moduleCode: {
      type: String,
      default: '',
    },
  });

  const { createMessage } = useMessage();

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const dataRef = ref<Recordable>({
    btnDisplayShow: '1',
    btnDelShow: '1',
    btn_log_show: '1',
    btnFlowShow: '1',
    btnEditShow: '1',
    btnAddShow: '1',
    isColOperateShow: 'true',
    isColOperateTextShow: false,
    isReplyEnabled: false,
    replyModule: '',
    likeMode: 0,
  });
  const state = ref<State>({
    isSpinning: false,
    loading: false,
  });

  const fetch = async () => {
    await nextTick();
    await resetFields();
    await getFormGetFieldsData();
    getVisualGetModulePropsData();
    getFormGetFieldsByBasicTreeData();
    getFormGetFieldsByDateData();

    let opts = await getFormViewList({ formCode: props.formCode });
    opts.forEach((item) => {
      item.value = '' + item.id;
      item.label = item.name;
    });
    let optsShow = [
      {
        value: '0',
        label: '默认',
      },
      {
        value: '1000002',
        label: '树形视图',
      },
      // {
      //   value: '1000001',
      //   label: '自定义',
      // },
      ...opts,
    ];
    updateSchema([
      {
        field: 'viewShow',
        componentProps: {
          options: optsShow,
        },
      },
    ]);

    let optsEdit = [
      {
        value: '0',
        label: '默认',
      },
      // {
      //   value: '1000000',
      //   label: '自定义',
      // },
      ...opts,
    ];
    updateSchema([
      {
        field: 'viewEdit',
        componentProps: {
          options: optsEdit,
        },
      },
    ]);
  };

  const fieldsByBasicTreeData = ref([]);
  //获取数据树
  const getFormGetFieldsByBasicTreeData = async () => {
    const data = (await getFormGetFieldsByBasicTree({ formCode: props.formCode })) || [];
    console.log('data', data);
    fieldsByBasicTreeData.value = data;
    fieldsByBasicTreeData.value.forEach((item) => {
      delete item.options;
    });
  };
  const fieldsByDates = ref<Recordable[]>([]);
  //获取日期型字段
  const getFormGetFieldsByDateData = async () => {
    const data = (await getFormGetFieldsByDate({ formCode: props.formCode })) || [];
    console.log('fieldsByDates', data);
    fieldsByDates.value = data;
    fieldsByDates.value.forEach((item) => {
      delete item.options;
    });
    fieldsByDates.value.unshift({
      name: '',
      title: '无',
    });
  };

  //获取模块信息
  const getVisualGetModulePropsData = async () => {
    try {
      if (!props.moduleCode) return;
      state.value.isSpinning = true;
      const res = await getVisualGetModuleProps({ moduleCode: props.moduleCode });
      if (res) {
        dataRef.value = res;
        dataRef.value.code = props.moduleCode;
        if (dataRef.value.gridShowField && dataRef.value.gridShowField.length) {
          dataRef.value.gridShowField = dataRef.value.gridShowField.split(',');
        } else {
          dataRef.value.gridShowField = [];
        }
        setFieldsValue({ ...dataRef.value });
      }
      console.log('getVisualGetModulePropsData', res);
    } catch (err) {
      console.error('getVisualGetModulePropsData', err);
    } finally {
      state.value.isSpinning = false;
    }
  };
  const formGetFieldsData = ref<Recordable[]>([]);
  //获取数据
  const getFormGetFieldsData = () => {
    formGetFieldsData.value = [];
    try {
      if (!props.formCode) return;
      getFormGetFields({ formCode: props.formCode }).then((res) => {
        formGetFieldsData.value = res || [];
        formGetFieldsData.value.forEach((item: Recordable) => {
          delete item.options;
          item.value = item.name;
          item.label = item.title;
        });

        formGetFieldsData.value.unshift({
          name: '',
          title: '无',
          value: '',
          label: '无',
        });
      });
    } catch (err) {
      console.error('getFormGetFields', err);
    }
  };
  onMounted(fetch);

  const handlecCearExportColProps = async (field) => {
    try {
      const params = {
        moduleCode: props.moduleCode,
      };
      state.value.loading = true;
      await getVisualClearExportColProps(params);
      setFieldsValue({ [field]: 0 });
      createMessage.success('操作成功');
    } catch (error) {
      console.log('handlecCearExportColProps', error);
    } finally {
      state.value.loading = false;
    }
  };

  const [registerModalConfiguration, { openModal: openConfiguration }] = useModal();
  //配置
  const handleConfiguration = (field) => {
    openConfiguration(true, {
      type: field,
      list: dataRef.value[field] || [],
      formGetFieldsData: formGetFieldsData.value,
    });
  };
  //配置回调
  const handleSuccessConfiguration = ({ field, value }) => {
    dataRef.value[field] = value;
    // setFieldsValue({ [field]: value });
  };

  const handleSuccess = () => {
    getVisualGetModulePropsData();
  };

  //提醒人员

  const [registerModalReminderPersonnelModal, { openModal: openReminderPersonnelModal }] =
    useModal();
  //配置
  const handleReminderPersonnelModal = (val) => {
    openReminderPersonnelModal(true, {
      fields: formGetFieldsData.value,
      msgProps: val,
      formCode: props.formCode,
    });
  };
  //配置回调
  const handleSuccessReminderPersonnelModal = async (val) => {
    try {
      state.value.loading = true;
      await getVisualSetMsgProp({ code: props.moduleCode, msgProp: val });
      createMessage.success('操作成功');
      handleSuccess();
    } catch (error) {
    } finally {
      state.value.loading = false;
    }
  };

  const go = useGo();
  //打开
  const handleOpen = () => {
    go({
      path: '/smartModulePage',
      query: {
        moduleCode: props.moduleCode,
      },
    });
  };

  const handleAllModule = () => {
    let title = '';
    if (currentRoute.value?.query?.title) {
      title = `${currentRoute.value.query.title}`;
    }
    go({
      path: '/formModule',
      query: {
        formCode: props.formCode,
        title: title,
        cacheName: `formModule${props.formCode}`,
      },
    });
  };

  const handleOk = async () => {
    try {
      const values = await validate();
      const data = Object.assign({}, dataRef.value, values);
      const formData: any = setFormData(data);
      if (isArray(formData.gridShowField) && formData.gridShowField.length) {
        formData.gridShowField = formData.gridShowField.join(',');
      }
      console.log('formData', formData);
      state.value.loading = true;
      await getVisualSetModuleProps(formData);
      createMessage.success('操作成功');
      handleSuccess();
    } catch (error) {
      console.error('handleOk', error);
    } finally {
      state.value.loading = false;
    }
  };
</script>
<style lang="less" scoped>
  .flex_gap {
    display: flex;
    gap: 10px;
    &_flex_1 {
      flex: 1;
    }
  }
  :deep(.ant-empty-normal) {
    margin: 0;
  }
</style>
